//
//  MyHeadView.m
//  HarmonizePub
//
//  Created by rzhy on 2016/11/15.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "MyHeadView.h"
#import "Config.h"
#import "User.h"

static CGFloat const height = 180.0f;

@interface MyHeadView ()
@property (weak, nonatomic) IBOutlet UIImageView *bgView;

@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconTopLayoutConstraint;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (nonatomic, strong) TouchImageEventBlock touchImageEventBlock;

@end

@implementation MyHeadView

+ (instancetype)headViewWithTouchImageEventBlock:(TouchImageEventBlock)touchImageEventBlock {
    MyHeadView *headView = [[NSBundle mainBundle] loadNibNamed:@"MyHeadView" owner:nil options:nil].lastObject;
    headView.touchImageEventBlock = touchImageEventBlock;
    return headView;
}

+ (CGFloat)height {
    return height;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchImageEvent)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.iconView addGestureRecognizer:tap];
}

- (void)setFrame:(CGRect)frame {
    frame.size.width = XHScreenWidth;
    frame.size.height = height;
    [super setFrame:frame];
}

- (void)setUser:(User *)user {
    _user = user;
    if (user) {
        self.titleLabel.text = user.name;
        self.titleLabel.textColor = [UIColor whiteColor];
        self.loginButton.hidden = YES;
        self.iconTopLayoutConstraint.constant = 40.0f;
        [self.iconView downloadImageWithURLString:user.icon placeholderString:@"UserIcon.png"];
    } else {
        self.iconTopLayoutConstraint.constant = 30.0f;
        self.titleLabel.text = @"用户，您好！";
        self.titleLabel.textColor = [UIColor blackColor];
        self.loginButton.hidden = NO;
        self.iconView.image = [UIImage imageNamed:@"UserIcon.png"];
    }
}

#pragma mark - touch event
#pragma mark icon
- (void)touchImageEvent {
    if (self.user)
        self.touchImageEventBlock();
    else
        [self loginEvent:nil];
}

#pragma mark login
- (IBAction)loginEvent:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(headViewTouchLoginButtonEvent:)])
        [self.delegate headViewTouchLoginButtonEvent:self];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.iconView.layer.cornerRadius = self.iconView.frame.size.width * 0.5;
    self.iconView.layer.masksToBounds = YES;
}

@end
